package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求Url
        String url = request.getURI().getPath();
        //判断是否鉴权
        //如果是url带有/login不需要拦截,直接放行
        if(url.contains("/login")){
            return chain.filter(exchange);
        }
        //剩下的不带login进行拦截
        //获取请求头
        String token = request.getHeaders().getFirst("token");
        //判断是否包含token
        //如果没有则返回401
        if(StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //有token,需要jwt验证token是否有效
        try{
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int token1 = AppJwtUtil.verifyToken(claims);
            if(token1 == -1||token1 == 0){
                //token有效,获取当前token中用户id,将usrId放入到请求头中转发到后端的微服务,放行
                Object userId = claims.get("userId");
                Object userName = claims.get("userName");
                request.mutate().header("userId",userId.toString());
                request.mutate().header("name",userName.toString());
                return chain.filter(exchange);
            }
        }catch (Exception e){
            // 记录错误日志
            log.error(e.getMessage());
        }
        //其他情况,统一返回401未授权
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
